/**
 * 条形图最大宽度， 这里和theme里的保持一致
 * @type {number}
 */
const BAR_MAX_WIDTH = 20;

/**
 * 条形图最小宽度， 这里和theme里的保持一致
 * @type {number}
 */
const BAR_MIN_WIDTH = 10;

/**
 * 自定义series的 工字图标绘制
 */
const toRenderItem = function (params, api, other) {
    const {
        seriesIndex,
        howManySeries,
        barCategoryGap,
        barGapPercentage,
        barMaxWidth,
        barMinWidth,
    } = other;
    const xValue = api.value(0);
    const highPoint = api.coord([api.value(1), xValue]);
    // const lowPoint = api.coord([api.value(2), xValue]);
    // const halfWidth = api.size([1, 0])[1] * 0.1;
    const categoryWidth = api.size([1, 0])[1];
    const style = api.style({
        stroke: api.visual('color'),
        fill: undefined
    });

    const howManyGapBetweenSeries = howManySeries - 1;

    let categoryStart = highPoint[1] - categoryWidth / 2 + barCategoryGap / 2;
    let categoryEnd = highPoint[1] + categoryWidth / 2 - barCategoryGap / 2;
    let netWidth = categoryEnd - categoryStart;
    const barGapRatio = barGapPercentage / 100;
    let netBarWidth = netWidth / (howManySeries + howManyGapBetweenSeries * barGapRatio);
    let netBarGapWidth = netBarWidth * barGapRatio;

    // barWidth大于barMaxWidth或者小于barMinWidth ，参数需要重新倒推
    if (netBarWidth > barMaxWidth || netBarWidth < barMinWidth) {
        if (netBarWidth > barMaxWidth) {
            netBarWidth = barMaxWidth;
        } else {
            netBarWidth = barMinWidth;
        }
        netBarGapWidth = netBarWidth * barGapRatio;
        netWidth = netBarWidth * howManySeries + netBarGapWidth * howManyGapBetweenSeries;
        categoryStart = highPoint[1] - netWidth / 2;
        // categoryEnd = highPoint[1] + netWidth / 2;
    }

    const children = [];
    const space = netBarGapWidth / 4;
    const x = highPoint[0];
    const upY = categoryStart + netBarWidth * seriesIndex + netBarGapWidth * seriesIndex - space;
    const downY = categoryStart + netBarWidth * seriesIndex + netBarGapWidth * seriesIndex + netBarWidth + space;
    const shortHorizontalLineLength = 3; // 短横线长度
    children.push({
        type: 'line', //长竖线
        transition: ['shape'],
        shape: {
            x1: x,
            y1: upY,
            x2: x,
            y2: downY,
        },
        style: style
    });
    children.push({
        type: 'line', //短上横线
        transition: ['shape'],
        shape: {
            x1: x - shortHorizontalLineLength,
            y1: upY,
            x2: x + shortHorizontalLineLength,
            y2: upY,
        },
        style: style
    });
    children.push({
        type: 'line', //短下横线
        transition: ['shape'],
        shape: {
            x1: x - shortHorizontalLineLength,
            y1: downY,
            x2: x + shortHorizontalLineLength,
            y2: downY,
        },
        style: style
    });

    return {
        type: 'group',
        children,
    };
};

const toCustomSeries = function (seriesName, seriesIndex, howManySeries, barCategoryGap, barGapPercentage, targetData) {
    const processedTargetData = targetData.map((t, index) => [index, t]);
    return {
        type: 'custom',
        name: seriesName,
        renderItem: function (params, api) {
            const other = {
                seriesIndex: seriesIndex,
                howManySeries,
                barCategoryGap,
                barGapPercentage,
                barMaxWidth: BAR_MAX_WIDTH,
                barMinWidth: BAR_MIN_WIDTH,
            };
            return toRenderItem(params, api, other);
        },
        data: processedTargetData,
        z: 100,
    };
};

function toBarCategoryGap(chartHeight, howManySeries, howManyCategory){
    return chartHeight / (howManySeries * howManyCategory);
}

function toSeries(chart, string_keys, casted_values, aggregate_data) {
    const howManyCategory = string_keys.length;
    const howManySeries = aggregate_data.length / 2;
    const barCategoryGap = toBarCategoryGap(chart.getHeight(), howManySeries, howManyCategory);
    const barGapPercentage = 50; // barGap百分比，可以调整

    // 遵循一个柜子 index % 2为0是实际值， 为1是目标值，  实际值的下一行是目标值
    const series = casted_values.flatMap(function (key, seriesIndex) {
        // 奇数行是目标值，跳过
        if (seriesIndex % 2 === 1) {
            return [];
        }

        const actualValueName = key.join("-");
        const targetValueName = casted_values[seriesIndex + 1].join("-");

        const seriesData = aggregate_data[seriesIndex].map(function (d) {
            return Number(d);
        });
        // 实际值的下一行就是目标值
        // aggregate_data[seriesIndex + 1]
        // aggregate_data[seriesIndex + 1]
        const columnNameList =aggregate_data[seriesIndex + 1].map(function (target, columnIndex) {
            return string_keys[columnIndex];
        });

        const targetData = aggregate_data[seriesIndex + 1].map(function (target) {
            return Number(target);
        });

        const actualTooltipFormatter = function (value) {
            let index = value.dataIndex;
            const columnName = columnNameList[index];
            const label = `${columnName}-${actualValueName}`;
            const actualValue = seriesData[index];
            return `${label}<br/><br/>${actualValue}`;
        };
        const targetTooltipFormatter = function (value) {
            let index = value.dataIndex;
            const columnName = columnNameList[index];
            const label = `${columnName}-${targetValueName}`;
            const targetValue = targetData[index];
            return `${label}<br/><br/>${targetValue}`;
        };

        // 实际值series
        const actualSeries = {
            name: actualValueName,
            type: "bar",
            barGap: barGapPercentage + '%',
            barCategoryGap: barCategoryGap,
            tooltip: {
                formatter: actualTooltipFormatter
            },
            yAxisIndex: 0, //对应第一个不显示的坐标轴
            data: seriesData,
            itemStyle: {
                borderRadius: 0,
            },
        };

        // 目标值series
        const targetSeries = {
            // 自定义series
            ...toCustomSeries(targetValueName, seriesIndex/ 2, howManySeries, barCategoryGap, barGapPercentage, targetData),
            tooltip: {
                formatter: targetTooltipFormatter
            },
        };

        // 用于撑开刻度的隐形series，
        const seriesForExpandTick = {
            name: targetValueName,
            type: "bar",
            barGap: barGapPercentage + '%',
            barCategoryGap: barCategoryGap,
            yAxisIndex: 1, //对应第二个不显示的坐标轴
            data: targetData,
            silent: true, //禁止响应事件
            itemStyle: {
                normal: {
                    color: "rgba(0,0,0,0)" /* 设置bar为透明色隐藏*/,
                },
            }
        };
        return [actualSeries, targetSeries, seriesForExpandTick];
    });

    return series;
}

const createMarkerOption = function (data, theme, chart) {

    const chartConfig = data.chartConfig;
    const casted_keys = data.keys;
    const casted_values = data.series;
    const aggregate_data = data.data;
    const newValuesConfig = data.seriesConfig;
    // const tunningOpt = chartConifg.option;
    const string_keys = casted_keys.map(function (key) {
        return key.join ? key.join("-") : key;
    });
    const series = toSeries(chart, string_keys, casted_values, aggregate_data);

    return {
        // ...chartConfig,
        tooltip: {},
        yAxis: [
            {
                type: "category",
                data: string_keys,
                axisPointer: {
                    type: "shadow",
                },
            },
            {
                //专门为了调整刻度大小，避免目标值和实际值差距过大时不在显示范围内
                //这个坐标轴不显示出来
                type: "category",
                data: string_keys,
                axisLabel: {
                    show: false,
                },
                axisLine: {
                    show: false,
                },
                axisTick: {
                    show: false,
                },
                splitArea: {
                    show: false,
                },
                splitLine: {
                    show: false,
                },
                axisPointer: {
                    type: "none",
                },
            },
        ],
        xAxis: {},
        series: series
    }
};

const changeSize = function (chart) {
    // const oldOption = chart.getOption();
    // const mySeries = oldOption.series;
    // const columnCount = oldOption.yAxis[0].data.length;
    // const seriesCount = mySeries.length;
    // mySeries.forEach(s => {
    //     if (s.markPoint) {
    //         s.markPoint.symbolSize = toMarkPointSymbolSize(chart, columnCount, seriesCount);
    //     }
    // });
    // chart.setOption({
    //     series: mySeries
    // });
};

export default {
    createOption: createMarkerOption,
    changeSize,
};
